import jsYaml, { Type } from "js-yaml";

type MaterialItem = {
  // 数量
  quantity: number;
  // 类型ID
  typeID: number;
};

type SkillLevel = {
  // 等级
  level: number;
  // 类型ID
  typeID: number;
};

export type YAMLActivity = {
  // 输入
  materials?: MaterialItem[];
  // 产出
  products?: MaterialItem[];
  // 制造时间
  time: number;
  //所需技能
  skills?: SkillLevel[];
};

export type YAMLBlueprints = {
  // 蓝图类型ID
  blueprintTypeID: number;
  // 最大生产限制
  maxProductionLimit: number;
  activities: {
    //拷贝
    copying?: YAMLActivity;
    //发明
    invention: YAMLActivity;
    //反应
    reaction: YAMLActivity;
    //制造
    manufacturing?: YAMLActivity;
    //蓝图材料研究
    research_material?: YAMLActivity;
    //蓝图制造时间研究
    research_time?: YAMLActivity;
  };
};

export type YAMLYAMLBlueprintsMap = Record<number, YAMLBlueprints>;

export const YAMLBlueprintsSchema = jsYaml.DEFAULT_SCHEMA.extend([
  new Type("!YAMLBlueprintsMap", {
    kind: "mapping",
    construct: (data: YAMLBlueprints) => {
      data.blueprintTypeID = Number(data.blueprintTypeID);
      data.maxProductionLimit = Number(data.maxProductionLimit);
      if (data.activities.copying) {
        data.activities.copying.time = Number(data.activities.copying.time);
      }
      if (data.activities.research_material) {
        data.activities.research_material.time = Number(data.activities.research_material.time);
      }
      if (data.activities.research_time) {
        data.activities.research_time.time = Number(data.activities.research_time.time);
      }
      [data.activities.research_time, data.activities.research_material].forEach((activity) => {
        activity?.materials?.forEach((item) => {
          item.quantity = Number(item.quantity);
          item.typeID = Number(item.typeID);
        });
        activity?.skills?.forEach((item) => {
          item.level = Number(item.level);
          item.typeID = Number(item.typeID);
        });
      });
      [(data.activities.invention, data.activities.reaction, data.activities.manufacturing)].forEach((activity) => {
        if (activity) {
          activity.time = Number(activity.time);
          [activity.materials, activity.products]
            .filter((i) => i)
            .flatMap((e) => e)
            .forEach((item) => {
              if (item) {
                item.quantity = Number(item.quantity);
                item.typeID = Number(item.typeID);
              }
            });
        }
      });

      return data;
    },
    instanceOf: Object,
    represent: (data: any) => data,
  }),
]);
